#include "head.h"

int exitPipe[2]; 
void hanlder(int signum){
    printf("signum = %d\n", signum);
    write(exitPipe[1],"1",1);
}

int main(int argc,char* argv[]){
    ARGS_CHECK(argc,4);

    char* ip=argv[1];
    char* port=argv[2];
    int listenfd = initTcp(ip,port); 

    int workerNum=atoi(argv[3]);
    workerData_t* workerArr=(workerData_t *) calloc(workerNum,sizeof(workerData_t));
    makeWorker(workerNum,workerArr);

    //快速打断
    pipe(exitPipe);
    signal(SIGUSR1,hanlder);

    
    int epfd=epoll_create(1);
    epoll_add(epfd,listenfd);
    for(int i=0;i<workerNum;i++){
        epoll_add(epfd,workerArr[i].pipefd);
    }
    epoll_add(epfd,exitPipe[0]);
    struct epoll_event readySet[1024]={0};
    while(1){
        int Num=epoll_wait(epfd,readySet,1024,-1);
        for(int i=0;i<Num;i++){
            // int curfd=readySet[i].data.fd;
            // printf("1 client connect, curfd=%d\n",curfd);
            if(readySet[i].data.fd==listenfd){
                int curfd=accept(listenfd,NULL,NULL);
                printf("1 client connect, curfd=%d\n",curfd);
                for(int j=0;j<workerNum;j++){
                    if(workerArr[j].status==FREE){
                        int flag=0;
                        printf("NO. %d worker gets his job,pid=%d\n",j,workerArr[j].pid);
                        sendfd(workerArr[j].pipefd,&flag,curfd);
                        workerArr[j].status=BUSY;
                        break;
                    }
                }
                close(curfd);
            }else if(readySet[i].data.fd==exitPipe[0]){
                printf("Process pool is going to exit!\n");
                for(int j=0;j<workerNum;j++){
                    // kill(workerArr[j],SIGKILL); 太直接不够优雅。
                    int flag=1;
                    sendfd(workerArr[j].pipefd,&flag,0); //要改此函数 已经改完
                }
                for(int x=0;x<workerNum;x++){
                    wait(NULL);
                }
                printf("all worker processes have exited!");
                free(workerArr);
                exit(0);

            }else{
                puts("One worker finish his task!");
                for(int j=0;j<workerNum;j++){
                    if(workerArr[j].pipefd==readySet[i].data.fd){
                        pid_t pid=-1;
                        recv(workerArr[j].pipefd,&pid,sizeof(pid),0);
                        printf("收到工人进程pid，pid=%d\n",pid);
                        workerArr[j].status=FREE;
                        break;
                    }
                }
            }
        }
    }
    return 0;
}